package kr.hkit.powerjava.algorithm;

import java.util.Arrays;
import java.util.Random;

public class BinarySerch {
	private int left;
	private int right;
	private int[] arrBinary;
	private Random rnd;

	public BinarySerch() {
		arrBinary = new int[10];
		rnd = new Random();
		left = 0;
		right = arrBinary.length - 1;
	}

	public void getNum() {
		for (int i = 0; i < arrBinary.length; i++) {
			int num = rnd.nextInt(50) + 1;
			if (isFind(num)) {
				i--;
			} else {
				arrBinary[i] = num;
			}
		}
	}

	public boolean isFind(int searchNum) {

		boolean isEquals = false; 

		for (int i = 0; i < arrBinary.length; i++) {
			if (searchNum == arrBinary[i]) { 
				isEquals = true;
				break;
			}
		}
		return isEquals;
	}

	public void prnNum() {
		for (int i = 0; i < arrBinary.length; i++) {
			Arrays.sort(arrBinary);
			System.out.print(arrBinary[i] + " ");
		}
		System.out.println();
	}

	public void getFound(int searchKey) {

		int mid = 0;
		int count = 0;

		do {
			count++;
			mid = (left + right) / 2;

			if (left > right) {
				System.out.println("찾는 값 없음!");
				break;
			} else if (searchKey > arrBinary[mid]) {
				left = mid + 1;
				System.out.println("Left: " + arrBinary[left] + " " + "Right: "
						+ arrBinary[right]);

			} else if (searchKey < arrBinary[mid]) {
				right = mid - 1;
				System.out.println("Left: " + arrBinary[left] + " " + "Right: "
						+ arrBinary[right]);

			} else if (searchKey == arrBinary[mid]) {
				System.out.println("숫자 " + arrBinary[mid] + " 찾았다!");
			}

		} while (searchKey != arrBinary[mid]);
		System.out.println("시도 횟수: " + count + "회");
	}
}
